package jdbc;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

public class TestJDBC2 {

    // MySQL 8.0 以下版本 - JDBC 驱动名及数据库 URL
    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
    static final String DB_URL = "jdbc:mysql://git.webturing.com:3306/how2java";

    // 数据库的用户名与密码，需要根据自己的设置
    static final String USER = "how2java";
    static final String PASS = "how2java";

    public static void main(String[] args) {
        Connection conn = null;
        Statement stmt = null;
        try {
            // 注册 JDBC 驱动
            Class.forName(JDBC_DRIVER);

            // 打开链接
            System.out.println("连接数据库...");
            conn = DriverManager.getConnection(DB_URL, USER, PASS);

            // 执行查询
            System.out.println(" 实例化Statement对象...");
            stmt = conn.createStatement();
            String sql;
            sql = "SELECT id, name FROM category_";
            ResultSet rs = stmt.executeQuery(sql);
            List<Category> cs = new ArrayList<>();
            // 展开结果集数据库
            while (rs.next()) {
                Category c = new Category();
                // 通过字段检索
                int id = rs.getInt("id");
                c.setId(id);
                String name = rs.getString("name");
                c.setName(name);
                // 输出数据

                cs.add(c);

            }
            for (Category c : cs) {
                System.out.print("ID: " + c.id);
                System.out.print(", name: " + c.name);
                System.out.print("\n");
            }
            // 完成后关闭
            rs.close();
            stmt.close();
            conn.close();
        } catch (SQLException se) {
            // 处理 JDBC 错误
            se.printStackTrace();
        } catch (Exception e) {
            // 处理 Class.forName 错误
            e.printStackTrace();
        } finally {
            // 关闭资源
            try {
                if (stmt != null) stmt.close();
            } catch (SQLException se2) {
            }// 什么都不做
            try {
                if (conn != null) conn.close();
            } catch (SQLException se) {
                se.printStackTrace();
            }
        }
        System.out.println("Goodbye!");
    }
}

class Category {
    int id;
    String name;

    public void setId(int id) {
        this.id = id;
    }

    public void setName(String name) {
        this.name = name;
    }
}